//
//  QRCodeController.m
//  HarmonizePub
//
//  Created by rzhy on 2017/7/12.
//  Copyright © 2017年 rzhy. All rights reserved.
//

#import "QRCodeController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "Config.h"
#import <YYModel.h>
#import "ZyBrda.h"
#import "QRCodeReaderView.h"
#import "WebViewController.h"

#import "PatientManagerController.h"

#if TARGET_IPHONE_SIMULATOR
BOOL Simulator = YES;
#else
BOOL Simulator = NO;
#endif

@interface QRCodeController () <QRCodeReaderViewDelegate, AVCaptureMetadataOutputObjectsDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    // 二维码扫描对象
    QRCodeReaderView *_readview;
    // 第一次进入该页面
    BOOL _isFirst;
    // 跳转到下一级页面
    BOOL _isPush;
}
@property (strong, nonatomic) CIDetector *detector;

@end

@implementation QRCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"扫描腕带";
    self.view.backgroundColor = [UIColor whiteColor];
    
    _isFirst = YES;
    _isPush = NO;
    
    if (Simulator) {
        [ZYToast showWithText:@"当前设备为模拟器，无法使用此功能，请使用真机!" bottomOffset:50.f duration:5.f];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self InitScan];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 扫描结果处理
- (void)accordingQcode:(NSString *)str {
//    XHLog(@"String: %@", str);
    if ([str hasPrefix:@"http"]) {
        [self setAlertViewWithMessage:@"二维码类型不符，请扫描腕带上的二维码!"];
    } else {
        [self getZyBrda:str];
    }
}

#pragma mark 查询病人信息.
- (void)getZyBrda:(NSString *)string {
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    NSDictionary *param = @{@"wdbm" : string};
    __weak typeof(self) weakSelf = self;
    [HTTPSTool POSTRequestWithPath:XHGetZyBrda cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"二维码病人信息: JSON -> %@", JSON);
        NSDictionary *dataDict = JSON[@"data"];
        ZyBrda *brda = [ZyBrda yy_modelWithJSON:dataDict];
        [weakSelf showPatientInfoAlertWithData:brda wdbm:string];
    }];
}

- (void)showPatientInfoAlertWithData:(ZyBrda *)brda wdbm:(NSString *)wdbm {
    NSString *message = [NSString stringWithFormat:@"病人姓名: %@\n病人科室: %@\n是否确认绑定?", brda.brxm, brda.zyks];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"查询成功" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf bindingZY:wdbm];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark 绑定病人.
- (void)bindingZY:(NSString *)wdbm {
    NSDictionary *param = @{@"wdbm" : wdbm};
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    __weak typeof(self) weakSelf = self;
    [HTTPSTool POSTRequestWithPath:XHBindZyBrda2 cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"JSON: %@", JSON);
        [weakSelf popToViewController];
    }];
}

- (void)popToViewController {
    NSArray *viewControllers = self.navigationController.childViewControllers;
    for (UIViewController *viewController in viewControllers) {
        if ([viewController isKindOfClass:[PatientManagerController class]]) {
            [self.navigationController popToViewController:viewController animated:YES];
            return ;
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 初始化扫描
- (void)InitScan {
    if (_readview) {
        [_readview removeFromSuperview];
        _readview = nil;
    }
    CGSize size = self.view.frame.size;
    _readview = [[QRCodeReaderView alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    _readview.is_AnmotionFinished = YES;
    _readview.backgroundColor = [UIColor clearColor];
    _readview.delegate = self;
    _readview.alpha = 0;
    
    [self.view addSubview:_readview];
    
    [UIView animateWithDuration:0.5 animations:^{
        _readview.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (!image) {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    _readview.is_Anmotion = YES;
    
    NSArray *features = [self.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    if (features.count >= 1) {
        [picker dismissViewControllerAnimated:YES completion:^{
            CIQRCodeFeature *feature = [features objectAtIndex:0];
            NSString *scannedResult = feature.messageString;
            // 播放扫描二维码的声音
            SystemSoundID soundID;
            NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"noticeMusic" ofType:@"wav"];
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile], &soundID);
            AudioServicesPlaySystemSound(soundID);
            
            [self accordingQcode:scannedResult];
        }];
        
    } else {
        [self setAlertViewWithMessage:@"该图片没有包含一个二维码！"];
        [picker dismissViewControllerAnimated:YES completion:^{
            _readview.is_Anmotion = NO;
            [_readview start];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - QRCodeReaderViewDelegate
- (void)readerScanResult:(NSString *)result {
    _readview.is_Anmotion = YES;
    [_readview stop];
    
    // 播放扫描二维码的声音
    SystemSoundID soundID;
    NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"noticeMusic" ofType:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID);
    AudioServicesPlaySystemSound(soundID);
    
    [self accordingQcode:result];
    
    [self performSelector:@selector(reStartScan) withObject:nil afterDelay:1.5];
}

- (void)reStartScan {
    _readview.is_Anmotion = NO;
    
    if (_readview.is_AnmotionFinished) {
        [_readview loopDrawLine];
    }
    
    [_readview start];
}

#pragma mark - view
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (_isFirst || _isPush) {
        if (_readview) {
            [self reStartScan];
        }
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    if (_readview) {
        [_readview stop];
        _readview.is_Anmotion = YES;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (_isFirst) {
        _isFirst = NO;
    }
    if (_isPush) {
        _isPush = NO;
    }
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)msg {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
